enyo.kind({
	name: "enyo.CreateAssessmentSummary",
	kind: enyo.PanelBase,
	
	components: [
		{kind: "PanelContent", headerContent: "Request Summary", onSignOut: "doSignOut", submitLeftContent: "Run", onSubmitLeft: "submitLeft", submitRightContent: "", onSubmitRight: "submitRight", onBack: "back", flex: 1, components: [
			{className: "margin-medium", components: [
				{kind: "Dialog", components: [
					{content: "Are you sure to submit the request?", style: "padding-left: 10px"},
					{layoutKind: "HFlexLayout", pack: "center", style: "padding: 10px;" , components: [
						{kind: "Button", caption: "OK", onclick: "okButtonClicked", className: "black-bg"},
						{kind: "Button", caption: "Cancel", onclick: "cancelButtonClicked", className: "black-bg"}
					]}
				]},
				{kind : "DividerDrawer", caption : "Request Type", components : [
					{name: "typeContent", content : "", className: "divider-content"}, 
				]},
				{kind : "DividerDrawer", caption : "Customer Country", components : [
					{name: "countryContent", kind:"HtmlContent", content : "", className: "divider-content"}, 
				]},
				{kind : "DividerDrawer", caption : "Customer City", components : [
					{name: "cityContent", kind:"HtmlContent", content : "", className: "divider-content"}, 
				]},
				{kind : "DividerDrawer", caption : "Languages", components : [
					{name: "languageContent", kind:"HtmlContent", content : "", className: "divider-content"}, 
				]},
				{kind : "DividerDrawer", caption : "Devices", components : [
					{name: "deviceContent", kind:"HtmlContent", content : "", className: "divider-content"}, 
				]},
				{kind : "DividerDrawer", caption : "Notification Recipients", components : [
					{kind: "VirtualRepeater", name: "emailRepeater", onSetupRow: "emailRepeaterSetupRow", className: "divider-content", components: [
						{kind: "Item", layoutKind: "HFlexLayout", style: "border: none" ,components: [			
							{kind: "Image", src: "images/btn_del.png", onclick: "deleteButtonClicked", style: "margin-right: 10px"},
							{name: "caption"},
						]}
					]},
					{kind: "RowGroup", caption: "Add notification Recipients", components: [
						{kind: "Input", name: "newEmailInput", components: [
								{kind: "Button", caption: "ADD", onclick: "addButtonClicked"}
							],
							hint: "Click here to add..."
						}
					]}
				]},
				{kind : "DividerDrawer", caption : "Subscription", components : [
					{layoutKind: "HFlexLayout", className: "divider-content", components:[
						{flex: 1, content: "A Subscription is a Saved Analysis Request which can be scheduled or manually executed later"},
						{kind: "ToggleButton", status: false, "onLabel": "YES", "offLabel": "NO", onChange: "subscriptionToggled"}
					]},
					{name: "subscriptionSettings", showing: false,  components: [
						{kind: "RowGroup", caption: "Sybscription Title", components: [
							{kind: "Input", name: "titleInput", hint: "Input title of the subscription...."}
						]},
						{kind: "RowGroup", caption: "Frequency", components: [
							{kind: "ListSelector", name: "frequencyCodePicker", value: "Unscheduled", items: ["Unscheduled", "Monthly", "Weekly", "Daily"], onChange: "frequencyCodePickerChanged", className: "bold"},
							{kind: "ListSelector", name: "frequencyNumberPicker", value: "0", items: [], showing: false, onChange: "frequencyNumberPickerChanged", className: "bold"}
						]}
					]}
				]}
			]}
		]},
		
		{name: "createService", kind: "WebService", method: "POST", onSuccess: "createServiceGot", onFailure: "createServiceFailure" }
	],
	
	create: function() {
		this.inherited(arguments);
		this.initPanel();
	},
	
	submitLeft: function() {
		enyo.Data.runImmediality = true;
		
		if(!this.checkSubscriptionParam()) return;
	
		//Submit
		this.$.dialog.open();
	},
	
	submitRight: function() {
		enyo.Data.runImmediality = false;
		
		if(!this.checkSubscriptionParam()) return;
		
		//Save
		this.$.dialog.open();
	},
	
	checkSubscriptionParam: function() {
		if(enyo.Data.saveSubscription) {
			enyo.Data.subScriptionTitle = this.$.titleInput.value;
			if(enyo.Data.subScriptionTitle.length <= 0) {
				this.doError("Please input the subscription title!");
				return false;
			}
			/*
			if(enyo.Data.frequencyCode == null) {
				this.doError("No Frequency Code is Selected");
				return false;
			}
			if(enyo.Data.frequencyNum == null) {
				this.doError("No Frequency Number is Selected");
				return false;
			}
			*/
			return true;
		} else {
			return true;
		}
	},
	
	okButtonClicked: function() {
		this.$.dialog.close();
		this.submitRequest();
	},
	cancelButtonClicked: function() {
		this.$.dialog.close();
	},
	
	back: function() {
		this.parentWnd.switchView("create_device");
	},
	
	initPanel: function()
	{
		this.showScrim();
		
		//reset the controls display and status
		enyo.Data.notificationRecipients = [];
		enyo.Data.notificationRecipients.push(enyo.Data.current_user);
		enyo.Data.subScriptionTitle = null;
		enyo.Data.frequencyCode = 1;
		enyo.Data.frequencyNum = 1;
		enyo.Data.runImmediality = false;
		enyo.Data.saveSubscription = false;
		enyo.Data.newRequestID = -1;

		//Show Type
		this.$.typeContent.setContent(enyo.Data.selected_AnalysisTypePayload.defaultAnalysisTypeName);
		
		//Show Country
		this.$.countryContent.setContent(enyo.Data.selected_CountryName);
		
		//Show City
		this.$.cityContent.setContent(enyo.Data.selected_CityName);

		//Show language
		var languageList = "";
		for(var i = 0; i < enyo.Data.selected_AnalysisTypePayload.supportedLocales.length; i++) {
			var local = enyo.Data.selected_AnalysisTypePayload.supportedLocales[i];
			if(local.checked) {
				languageList += local.displayedNameInEnglish + "; </br>";
			}
		}
		this.$.languageContent.setContent(languageList);
		
		//Sow Devices
		var deviceList = "";
		for(var i = 0; i < enyo.Data.payload_Devices.length; i++) {
			if(enyo.Data.payload_Devices.payloadChecked[i]) {
				deviceList += "<div class=\"break-all\">" + enyo.Data.payload_Devices[i].hostname + "; </div>";
			}
		}
		this.$.deviceContent.setContent(deviceList);

		this.hideScrim();
	},
	
	addButtonClicked: function() {
		var strEmail = this.$.newEmailInput.value;
		if(this.checkMail(strEmail)) {
			enyo.Data.notificationRecipients.push(strEmail);
			this.$.newEmailInput.setValue("");
			this.$.emailRepeater.render();
		}
		else {
			this.doError("Email address not valid.");
			this.$.newEmailInput.forceSelect();
		}
	},
	
	checkMail: function(strEmail) {
		var reg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
		return reg.test(strEmail);
	},
	
	emailRepeaterSetupRow: function(inSender, inIndex) {
		if(inIndex < enyo.Data.notificationRecipients.length) {
			this.$.caption.setContent(enyo.Data.notificationRecipients[inIndex]);
			return true;
		}
	},
	
	deleteButtonClicked: function(inSender, inEvent) {
		var index = inEvent.rowIndex;
		enyo.Data.notificationRecipients.splice(index, 1);
		this.$.emailRepeater.render();
	},
	
	subscriptionToggled: function(inSender, inState) {
		enyo.Data.saveSubscription = inState;
		this.$.subscriptionSettings.setShowing(enyo.Data.saveSubscription);
		
		this.$.panelContent.submitLeftContent = enyo.Data.saveSubscription ? "Save & Run" : "Run";
		this.$.panelContent.submitRightContent = enyo.Data.saveSubscription ? "Save" : "";
		this.$.panelContent.headerContentChanged();
	},
	
	frequencyCodePickerChanged: function(inSender, inIndex) {
		enyo.Data.frequencyCode = this.$.frequencyCodePicker.getValue();
		enyo.Data.frequencyNum = 1;
		var frequencyNumber = [];
		switch(enyo.Data.frequencyCode) {
			case "Unscheduled":
				this.$.frequencyNumberPicker.setShowing(false);
				break;
			case "Monthly":
				this.$.frequencyNumberPicker.setShowing(true);
				frequencyNumber.push({caption: "January", value: 1});
				frequencyNumber.push({caption: "February", value: 2});
				frequencyNumber.push({caption: "March", value: 3});
				frequencyNumber.push({caption: "April", value: 4});
				frequencyNumber.push({caption: "May", value: 5});
				frequencyNumber.push({caption: "June", value: 6});
				frequencyNumber.push({caption: "July", value: 7});
				frequencyNumber.push({caption: "August", value: 8});
				frequencyNumber.push({caption: "September", value: 9});
				frequencyNumber.push({caption: "October", value: 10});
				frequencyNumber.push({caption: "November", value: 11});
				frequencyNumber.push({caption: "December", value: 12});
				this.$.frequencyNumberPicker.setItems(frequencyNumber);
				this.$.frequencyNumberPicker.setValue(1);
				break;
			case "Weekly":
				this.$.frequencyNumberPicker.setShowing(true);
				frequencyNumber.push({caption: "Monday", value: 1});
				frequencyNumber.push({caption: "Tuesday", value: 2});
				frequencyNumber.push({caption: "Wednesday", value: 3});
				frequencyNumber.push({caption: "Thursday", value: 4});
				frequencyNumber.push({caption: "Friday", value: 5});
				frequencyNumber.push({caption: "Saturday", value: 6});
				frequencyNumber.push({caption: "Sunday", value: 7});
				this.$.frequencyNumberPicker.setItems(frequencyNumber);
				this.$.frequencyNumberPicker.setValue(1);
				break;
			case "Daily":
				this.$.frequencyNumberPicker.setShowing(true);
				for(var i = 1; i<= 28; i++) frequencyNumber.push({caption: i, value: i});
				this.$.frequencyNumberPicker.setItems(frequencyNumber);
				this.$.frequencyNumberPicker.setValue(1);
				break;
		}
	},
	
	frequencyNumberPickerChanged: function(inSender, inIndex) {
		enyo.Data.frequencyNum = this.$.frequencyNumberPicker.getValue();
	},
	
	submitRequest: function() {
		var objValue1 = new Object;
		
		//Check if there is not recipient
		if(enyo.Data.notificationRecipients.length <= 0) {
			enyo.Data.notificationRecipients.push(enyo.Data.current_user);
		}
		
		objValue1.analysisTypeCode = enyo.Data.selected_AnalysisTypePayload.analysisTypeCode;	//Type code of type
		
		//Selected language
		objValue1.localCodeList = [];
		for(var i = 0; i < enyo.Data.selected_AnalysisTypePayload.supportedLocales.length; i++) {
			var local = enyo.Data.selected_AnalysisTypePayload.supportedLocales[i];
			if(local.checked) {
				objValue1.localCodeList.push(local.localeCode);
			}
		}
		
		//Selected device
		objValue1.deviceMoosKeys = [];
		for(var i = 0; i < enyo.Data.payload_Devices.length; i++) {
			if(enyo.Data.payload_Devices.payloadChecked[i]) {
				objValue1.deviceMoosKeys.push(enyo.Data.payload_Devices[i].moosKey);
			}
		}
		
		objValue1.organizationSiteInternalKey = enyo.Data.selected_CustomerOrgSiteKey;	//Org site id
		
		//notification recipients
		objValue1.notificationRecipientAccountIdentifierList = [];
		for(var i = 0; i < enyo.Data.notificationRecipients.length; i++) {
			objValue1.notificationRecipientAccountIdentifierList.push(enyo.Data.notificationRecipients[i]);
		}
		
		objValue1.runImmediately = enyo.Data.runImmediality;
		objValue1.saveSubscription = enyo.Data.saveSubscription;
		objValue1.subscriptionTitle = enyo.Data.subScriptionTitle;
		objValue1.frequencyCode = enyo.Data.frequencyCode;
		objValue1.frequencyNumber = enyo.Data.frequencyNum;
		
		var obj = new Object;
		obj.value0 = "mobile.test";
		obj.value1 = enyo.json.stringify(objValue1);
		
		this.showScrim();
		
		//call the service
		this.$.createService.setUrl(enyo.Config.getServiceUrl_CreateAnalysisRequest());
		this.$.createService.setHeaders(enyo.Config.getCommonServiceHeader());
		this.$.createService.call(obj);
	},
	
	createServiceGot: function(inSender, inResponse, inRequest) {
		this.serviceResponse = inResponse;
		if(this.serviceResponse.statusCode === 200) {
			if(inResponse.payload > 0) {
				enyo.Data.newRequestID = inResponse.payload;	//store the new request ID
				this.parentWnd.switchView("create_result");
			} else {
				this.doError("ERROR: requestID:" + enyo.Data.newRequestID);
			}
			this.hideScrim();	//finally, initialize work done, chagne the UI
		}
		else {
			this.doError("Error response of service (StatusCode: " + inResponse.statusCode + ")");
		}
	},
	
	createServiceFailure: function(inSender, inResponse, inRequest) {
		this.doError("Failed calling service");
	},
});